﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Net.Sockets;
using System.Text;
using IPAddress = System.Net.IPAddress;

namespace MDT.LifeSewagePlatform.Conmmon
{
    public class SocketHelper : ISocketHelper
    {
        [Autowired]
        private IConfiguration Configuration { get; set; }
        [Autowired]
        private ILogger<SocketHelper> logger { get; set; }
        public int Prot { get; set; }
        public IPAddress Ip { get; set; }
        public Socket ClientSocket { get; set; }
        public SocketHelper()
        {

        }
        private void Init()
        {
            try
            {

                if (Prot > 0 || Ip == null)
                {
                    Prot = int.Parse(Configuration["BuilderImageProt"]);
                    Ip = IPAddress.Parse(Configuration["BuilderImageIp"]);
                    ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    ClientSocket.Connect(Ip, Prot);
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                logger.LogError(ex.InnerException != null ? ex.InnerException.Message : "");
            }


        }

        public bool Send(string json)
        {
            if (ClientSocket==null)
            {
                Init();
            }
            int res = 0;
            if (ClientSocket != null)
            {
                byte[] bys = Encoding.UTF8.GetBytes(json);
                res = ClientSocket.Send(bys);
            }
            return res > 0;
        }

        public bool Send(DataModel data)
        {
            if (ClientSocket == null)
            {
                Init();
            }

            int res = 0;
            if (ClientSocket != null)
            {

                string json = JsonConvert.SerializeObject(data);
                byte[] bys = Encoding.UTF8.GetBytes(json);
                res = ClientSocket.Send(bys);
            }
            return res > 0;
        }

        public void Close()
        {
            ClientSocket.Close();
            ClientSocket.Dispose();
            ClientSocket = null;
        }

        public void Open()
        {
            Init();
        }

    }
}
